package com.luca.framework.web.service;

import com.luca.common.constant.Constants;
import com.luca.common.core.domain.model.LoginUser;
import com.luca.common.core.redis.RedisUtil;
import com.luca.common.enums.UserType;
import com.luca.common.exception.CustomException;
import com.luca.common.exception.user.CaptchaException;
import com.luca.common.exception.user.CaptchaExpireException;
import com.luca.common.exception.user.UserPasswordNotMatchException;
import com.luca.common.utils.MessageUtils;
import com.luca.common.utils.StringUtils;
import com.luca.framework.manager.AsyncManager;
import com.luca.framework.manager.factory.AsyncFactory;
import com.luca.framework.security.CustomerAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author luca
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    // 验证码是否启用
    private boolean checkCaptcha = false;

    /**
     * 登录验证
     *
     * @param code     租户代码
     * @param username 用户名
     * @param password 密码
     * @param captcha  验证码
     * @param uuid     唯一标识
     * @param userType 用户类型
     * @return 结果
     */
    public String login(String code, String username, String password, String captcha, String uuid, String userType) {
        Authentication authentication = null;
        UsernamePasswordAuthenticationToken token = null;
        // 租户管理员登录
        if (StringUtils.equals(UserType.TENANT_ADMIN.getCode(), userType)) {
            if (checkCaptcha) {
                checkCaptcha(username, uuid, captcha);
            }
            token = new CustomerAuthenticationToken(username, password, code);
        } else {
            token = new UsernamePasswordAuthenticationToken(username, password);
        }
        try {
            // 该方法会去调用 UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(token);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 验证码校验
     */
    private void checkCaptcha(String username, String uuid, String captcha) {
        // 验证码校验
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//        String redisCaptcha = redisUtil.getCacheObject(verifyKey);
        String redisCaptcha = (String) RedisUtil.valueOperations.get(verifyKey);
        RedisUtil.redisTemplate.delete(verifyKey);
//        redisUtil.deleteObject(verifyKey);
        if (redisCaptcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!captcha.equalsIgnoreCase(redisCaptcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }
}
